package com.tju.ocean_ecology_website.controller;

import com.tju.ocean_ecology_website.dto.ApiResponse;
import com.tju.ocean_ecology_website.dto.ProjectTypeDistributionDTO;
import com.tju.ocean_ecology_website.dto.ProjectTypeDistributionItemDTO;
import com.tju.ocean_ecology_website.dto.RecentActivityDTO;
import com.tju.ocean_ecology_website.dto.ServiceHoursTrendDTO;
import com.tju.ocean_ecology_website.dto.ServiceHoursTrendResponseDTO;
import com.tju.ocean_ecology_website.dto.UpcomingActivityDTO;
import com.tju.ocean_ecology_website.dto.VolunteerStatsDTO;
import com.tju.ocean_ecology_website.dto.VolunteerStatsResponseDTO;
import com.tju.ocean_ecology_website.entity.Activity;
import com.tju.ocean_ecology_website.entity.ActivitySignup;
import com.tju.ocean_ecology_website.entity.ActivityTag;
import com.tju.ocean_ecology_website.entity.TeamMember;
import com.tju.ocean_ecology_website.entity.User;
import com.tju.ocean_ecology_website.entity.VolunteerCertificate;
import com.tju.ocean_ecology_website.entity.VolunteerInfo;
import com.tju.ocean_ecology_website.entity.VolunteerServiceRecord;
import com.tju.ocean_ecology_website.mapper.UserMapper;
import com.tju.ocean_ecology_website.service.ActivityService;
import com.tju.ocean_ecology_website.service.ActivitySignupService;
import com.tju.ocean_ecology_website.service.ActivityTagService;
import com.tju.ocean_ecology_website.service.TeamMemberService;
import com.tju.ocean_ecology_website.service.UserService;
import com.tju.ocean_ecology_website.service.VolunteerCertificateService;
import com.tju.ocean_ecology_website.service.VolunteerInfoService;
import com.tju.ocean_ecology_website.service.VolunteerServiceRecordService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 志愿者首页Dashboard控制器
 */
@RestController
@RequestMapping("/api/volunteer")
public class VolunteerDashboardController {

    @Resource
    private UserService userService;

    @Resource
    private VolunteerInfoService volunteerInfoService;

    @Resource
    private VolunteerServiceRecordService volunteerServiceRecordService;

    @Resource
    private UserMapper userMapper;

    @Resource
    private ActivityService activityService;

    @Resource
    private ActivitySignupService activitySignupService;

    @Resource
    private TeamMemberService teamMemberService;

    @Resource
    private VolunteerCertificateService volunteerCertificateService;

    @Resource
    private ActivityTagService activityTagService;

    /**
     * 获取志愿者数据概览
     *
     * @return 志愿者数据概览
     */
    @GetMapping("/stats")
    public ResponseEntity<ApiResponse<VolunteerStatsResponseDTO>> getVolunteerStats() {
        // 获取当前用户ID
        Long currentUserId = getCurrentUserId();

        // 查询志愿者信息
        VolunteerInfo volunteerQuery = new VolunteerInfo();
        volunteerQuery.setUserId(currentUserId);
        Page<VolunteerInfo> volunteerInfoPage = volunteerInfoService.queryByPage(volunteerQuery, PageRequest.of(0, 1));

        // 查询服务时长
        int serviceHours = 0;
        if (!volunteerInfoPage.isEmpty()) {
            VolunteerInfo volunteerInfo = volunteerInfoPage.getContent().get(0);
            serviceHours = volunteerInfo.getVolunteerHours() != null ? volunteerInfo.getVolunteerHours() : 0;
        }

        // 查询参与项目数量
        ActivitySignup signupQuery = new ActivitySignup();
        signupQuery.setUserId(currentUserId);
        signupQuery.setStatus(1); // 已通过
        long projectCount = activitySignupService.count(signupQuery);

        // 查询加入团队数量
        TeamMember teamQuery = new TeamMember();
        teamQuery.setUserId(currentUserId);
        teamQuery.setStatus(0); // 活跃
        long teamCount = teamMemberService.count(teamQuery);

        // 查询获得证书数量，也就是获得表彰的数量
        VolunteerCertificate certificateQuery = new VolunteerCertificate();
        certificateQuery.setVolunteerId(currentUserId);
        certificateQuery.setStatus(0); // 有效
        long awardCount = volunteerCertificateService.count(certificateQuery);

        // 创建响应DTO
        VolunteerStatsResponseDTO responseDTO = VolunteerStatsResponseDTO.builder()
                .serviceHours(serviceHours)
                .projectCount((int) projectCount)
                .teamCount((int) teamCount)
                .awardCount((int) awardCount)
                .build();

        return ResponseEntity.ok(ApiResponse.success(responseDTO));
    }

    /**
     * 获取服务时长趋势
     *
     * @param timeRange 时间范围（week: 周, month: 月, quarter: 季度）
     * @return 服务时长趋势
     */
    @GetMapping("/hours/trend")
    public ResponseEntity<ApiResponse<ServiceHoursTrendResponseDTO>> getServiceHoursTrend(
            @RequestParam(value = "timeRange", defaultValue = "week") String timeRange) {

        // 获取当前用户ID
        Long currentUserId = getCurrentUserId();

        // 创建查询条件
        VolunteerServiceRecord recordQuery = new VolunteerServiceRecord();
        recordQuery.setVolunteerId(currentUserId);
        recordQuery.setStatus(1); // 只统计已认证的服务时长

        // 查询所有服务时长记录
        List<VolunteerServiceRecord> records = volunteerServiceRecordService.queryAll(recordQuery);

        // 根据时间范围生成日期列表和时长列表
        List<String> dates = new ArrayList<>();
        List<Integer> hours = new ArrayList<>();

        // 获取当前日期
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat;

        // 根据时间范围设置日期格式和生成日期列表
        switch (timeRange) {
            case "week":
                // 设置为本周的周一
                calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
                dateFormat = new SimpleDateFormat("E"); // 星期几

                // 生成本周的7天
                for (int i = 0; i < 7; i++) {
                    dates.add(dateFormat.format(calendar.getTime()));
                    hours.add(0); // 初始化为0
                    calendar.add(Calendar.DAY_OF_WEEK, 1);
                }

                // 重置日历
                calendar = Calendar.getInstance();
                calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
                Date weekStart = calendar.getTime();

                calendar.add(Calendar.DAY_OF_WEEK, 7);
                Date weekEnd = calendar.getTime();

                // 过滤本周的记录并统计
                for (VolunteerServiceRecord record : records) {
                    Date serviceDate = record.getServiceDate();
                    if (serviceDate != null && serviceDate.after(weekStart) && serviceDate.before(weekEnd)) {
                        Calendar serviceCalendar = Calendar.getInstance();
                        serviceCalendar.setTime(serviceDate);
                        int dayOfWeek = serviceCalendar.get(Calendar.DAY_OF_WEEK) - Calendar.MONDAY;
                        if (dayOfWeek >= 0 && dayOfWeek < 7) {
                            hours.set(dayOfWeek, hours.get(dayOfWeek) + record.getServiceHours());
                        }
                    }
                }

                // 将日期转换为中文
                List<String> chineseDates = new ArrayList<>();
                for (String date : dates) {
                    switch (date) {
                        case "Mon": chineseDates.add("周一"); break;
                        case "Tue": chineseDates.add("周二"); break;
                        case "Wed": chineseDates.add("周三"); break;
                        case "Thu": chineseDates.add("周四"); break;
                        case "Fri": chineseDates.add("周五"); break;
                        case "Sat": chineseDates.add("周六"); break;
                        case "Sun": chineseDates.add("周日"); break;
                        default: chineseDates.add(date);
                    }
                }
                dates = chineseDates;
                break;

            case "month":
                // 设置为本月的1号
                calendar.set(Calendar.DAY_OF_MONTH, 1);
                dateFormat = new SimpleDateFormat("d"); // 日期

                // 获取本月的天数
                int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

                // 生成本月的所有日期
                for (int i = 0; i < daysInMonth; i++) {
                    dates.add(dateFormat.format(calendar.getTime()) + "日");
                    hours.add(0); // 初始化为0
                    calendar.add(Calendar.DAY_OF_MONTH, 1);
                }

                // 重置日历
                calendar = Calendar.getInstance();
                calendar.set(Calendar.DAY_OF_MONTH, 1);
                Date monthStart = calendar.getTime();

                calendar.add(Calendar.MONTH, 1);
                Date monthEnd = calendar.getTime();

                // 过滤本月的记录并统计
                for (VolunteerServiceRecord record : records) {
                    Date serviceDate = record.getServiceDate();
                    if (serviceDate != null && serviceDate.after(monthStart) && serviceDate.before(monthEnd)) {
                        Calendar serviceCalendar = Calendar.getInstance();
                        serviceCalendar.setTime(serviceDate);
                        int dayOfMonth = serviceCalendar.get(Calendar.DAY_OF_MONTH) - 1;
                        if (dayOfMonth >= 0 && dayOfMonth < daysInMonth) {
                            hours.set(dayOfMonth, hours.get(dayOfMonth) + record.getServiceHours());
                        }
                    }
                }
                break;

            case "quarter":
                // 获取当前季度的起始月份
                int currentMonth = calendar.get(Calendar.MONTH);
                int quarterStartMonth = (currentMonth / 3) * 3;

                // 设置为季度的第一个月
                calendar.set(Calendar.MONTH, quarterStartMonth);
                calendar.set(Calendar.DAY_OF_MONTH, 1);
                dateFormat = new SimpleDateFormat("M"); // 月份

                // 生成季度的3个月
                for (int i = 0; i < 3; i++) {
                    dates.add(dateFormat.format(calendar.getTime()) + "月");
                    hours.add(0); // 初始化为0
                    calendar.add(Calendar.MONTH, 1);
                }

                // 重置日历
                calendar = Calendar.getInstance();
                calendar.set(Calendar.MONTH, quarterStartMonth);
                calendar.set(Calendar.DAY_OF_MONTH, 1);
                Date quarterStart = calendar.getTime();

                calendar.add(Calendar.MONTH, 3);
                Date quarterEnd = calendar.getTime();

                // 过滤本季度的记录并统计
                for (VolunteerServiceRecord record : records) {
                    Date serviceDate = record.getServiceDate();
                    if (serviceDate != null && serviceDate.after(quarterStart) && serviceDate.before(quarterEnd)) {
                        Calendar serviceCalendar = Calendar.getInstance();
                        serviceCalendar.setTime(serviceDate);
                        int month = serviceCalendar.get(Calendar.MONTH);
                        int monthIndex = month - quarterStartMonth;
                        if (monthIndex >= 0 && monthIndex < 3) {
                            hours.set(monthIndex, hours.get(monthIndex) + record.getServiceHours());
                        }
                    }
                }
                break;

            default:
                // 默认按周处理
                return getServiceHoursTrend("week");
        }

        // 创建响应DTO
        ServiceHoursTrendResponseDTO responseDTO = ServiceHoursTrendResponseDTO.builder()
                .dates(dates)
                .hours(hours)
                .build();

        return ResponseEntity.ok(ApiResponse.success(responseDTO));
    }

    /**
     * 获取当前志愿者报名的项目类型分布
     *
     * @return 项目类型分布
     */
    @GetMapping("/projects/distribution")
    public ResponseEntity<ApiResponse<List<ProjectTypeDistributionItemDTO>>> getProjectTypeDistribution() {
        // 获取当前用户ID
        Long currentUserId = getCurrentUserId();

        // 查询当前用户报名的活动
        ActivitySignup signupQuery = new ActivitySignup();
        signupQuery.setUserId(currentUserId);
        signupQuery.setStatus(1); // 已通过的报名
        List<ActivitySignup> signups = activitySignupService.queryAll(signupQuery);

        // 获取活动ID列表
        List<Long> activityIds = signups.stream()
                .map(ActivitySignup::getActivityId)
                .collect(Collectors.toList());

        // 统计活动标签
        Map<String, Integer> tagCounts = new HashMap<>();
        for (Long activityId : activityIds) {
            Activity activity = activityService.queryById(activityId);
            if (activity == null) continue;

            // 查询活动标签
            ActivityTag tagQuery = new ActivityTag();
            tagQuery.setActivityId(activity.getId());
            Page<ActivityTag> tagPage = activityTagService.queryByPage(tagQuery, PageRequest.of(0, 10));
            for (ActivityTag tag : tagPage.getContent()) {
                String tagName = tag.getTagName();
                tagCounts.put(tagName, tagCounts.getOrDefault(tagName, 0) + 1);
            }
        }

        // 排序并取前5个标签
        List<Map.Entry<String, Integer>> sortedTags = tagCounts.entrySet().stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                .limit(5)
                .collect(Collectors.toList());

        // 创建响应DTO列表
        List<ProjectTypeDistributionItemDTO> distributionItems = sortedTags.stream()
                .map(entry -> ProjectTypeDistributionItemDTO.builder()
                        .name(entry.getKey())
                        .value(entry.getValue())
                        .build())
                .collect(Collectors.toList());

        return ResponseEntity.ok(ApiResponse.success(distributionItems));
    }

    /**
     * 获取志愿者最近活动（当前志愿者报名的所有活动）
     *
     * @return 最近活动列表
     */
    @GetMapping("/activities/recent")
    public ResponseEntity<ApiResponse<List<RecentActivityDTO>>> getRecentActivities() {
        // 获取当前用户ID
        Long currentUserId = getCurrentUserId();

        // 查询当前用户报名的活动
        ActivitySignup signupQuery = new ActivitySignup();
        signupQuery.setUserId(currentUserId);
        signupQuery.setStatus(1); // 已通过的报名
        List<ActivitySignup> signups = activitySignupService.queryAll(signupQuery);

        // 如果没有报名记录，返回空列表
        if (signups.isEmpty()) {
            return ResponseEntity.ok(ApiResponse.success(new ArrayList<>()));
        }

        // 获取活动ID列表
        List<Long> activityIds = signups.stream()
                .map(ActivitySignup::getActivityId)
                .collect(Collectors.toList());

        // 查询活动详情
        List<Activity> activities = new ArrayList<>();
        for (Long activityId : activityIds) {
            Activity activity = activityService.queryById(activityId);
            if (activity != null) {
                activities.add(activity);
            }
        }

        // 按活动日期降序排序（最近的在前面）
        activities.sort(Comparator.comparing(Activity::getDate, Comparator.nullsLast(Comparator.naturalOrder())).reversed());

        // 创建活动DTO列表
        List<RecentActivityDTO> recentActivities = new ArrayList<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String[] types = {"primary", "success", "info", "warning"};
        int typeIndex = 0;

        for (Activity activity : activities) {
            String time = activity.getDate() != null ? dateFormat.format(activity.getDate()) : "";
            String type = types[typeIndex % types.length];
            typeIndex++;

            // 根据活动状态生成不同的内容
            String content;
            if (activity.getStatus() != null) {
                switch (activity.getStatus()) {
                    case 0: // 待开始
                        content = "已报名“" + activity.getTitle() + "”活动";
                        break;
                    case 1: // 进行中
                        content = "正在参与“" + activity.getTitle() + "”活动";
                        break;
                    case 2: // 已结束
                        content = "完成了“" + activity.getTitle() + "”活动";
                        break;
                    default:
                        content = "参与了“" + activity.getTitle() + "”活动";
                }
            } else {
                content = "参与了“" + activity.getTitle() + "”活动";
            }

            recentActivities.add(RecentActivityDTO.builder()
                    .id(activity.getId())
                    .content(content)
                    .time(time)
                    .type(type)
                    .build());
        }

        return ResponseEntity.ok(ApiResponse.success(recentActivities));
    }

    /**
     * 获取志愿者待参与活动（当前志愿者报名的待开始活动）
     *
     * @return 待参与活动列表
     */
    @GetMapping("/activities/upcoming")
    public ResponseEntity<ApiResponse<List<UpcomingActivityDTO>>> getUpcomingActivities() {
        // 获取当前用户ID
        Long currentUserId = getCurrentUserId();

        // 查询当前用户报名的活动
        ActivitySignup signupQuery = new ActivitySignup();
        signupQuery.setUserId(currentUserId);
        signupQuery.setStatus(1); // 已通过的报名
        List<ActivitySignup> signups = activitySignupService.queryAll(signupQuery);

        // 如果没有报名记录，返回空列表
        if (signups.isEmpty()) {
            return ResponseEntity.ok(ApiResponse.success(new ArrayList<>()));
        }

        // 获取活动ID列表
        List<Long> activityIds = signups.stream()
                .map(ActivitySignup::getActivityId)
                .collect(Collectors.toList());

        // 查询待开始的活动
        List<Activity> upcomingActivitiesList = new ArrayList<>();
        for (Long activityId : activityIds) {
            Activity activity = activityService.queryById(activityId);
            // 只添加状态为待开始的活动
            if (activity != null && activity.getStatus() != null && activity.getStatus() == 0) {
                upcomingActivitiesList.add(activity);
            }
        }

        // 按活动日期升序排序（最近的在前面）
        upcomingActivitiesList.sort(Comparator.comparing(Activity::getDate, Comparator.nullsLast(Comparator.naturalOrder())));

        // 创建活动DTO列表
        List<UpcomingActivityDTO> upcomingActivities = new ArrayList<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        for (Activity activity : upcomingActivitiesList) {
            String time = activity.getDate() != null ? dateFormat.format(activity.getDate()) : "";

            upcomingActivities.add(UpcomingActivityDTO.builder()
                    .id(activity.getId())
                    .name(activity.getTitle())
                    .time(time)
                    .build());
        }

        return ResponseEntity.ok(ApiResponse.success(upcomingActivities));
    }

    /**
     * 获取当前登录用户的ID
     *
     * @return 当前用户ID
     */
    private Long getCurrentUserId() {
        // 从 SecurityContextHolder 获取当前认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            // 获取用户名
            String username = authentication.getName();
            // 通过用户名查询用户信息
            User user = userMapper.findByUsername(username);
            if (user != null) {
                return user.getId();
            }
        }
        // 如果无法获取用户信息，抛出异常
        throw new RuntimeException("未能获取当前用户信息，请确保用户已登录");
    }
}
